from fastapi import APIRouter, HTTPException
from ..services.langchain_service import LangChainService
from ..models.request import ProcessRequest, ProcessResponse
from ..utils.logger import setup_logger
import os
import json

router = APIRouter()
logger = setup_logger('process_api')
langchain_service = LangChainService()

@router.post("/process/{filename}", response_model=ProcessResponse)
async def process_file(filename: str, request: ProcessRequest):
    """处理文件接口"""
    try:
        logger.info(f"收到处理请求 - 文件名: {filename}")
        logger.info(f"请求参数: {json.dumps(request.dict(), ensure_ascii=False, indent=2)}")
        
        # 检查temp_dir参数
        if not request.temp_dir:
            error_msg = "缺少temp_dir参数"
            logger.error(error_msg)
            raise HTTPException(status_code=400, detail=error_msg)
            
        # 检查temp_dir目录是否存在
        if not os.path.exists(request.temp_dir):
            error_msg = f"临时目录不存在: {request.temp_dir}"
            logger.error(error_msg)
            raise HTTPException(status_code=404, detail=error_msg)
        
        # 构建OCR文本文件路径
        ocr_text_path = os.path.join(request.temp_dir, "ocr", "text", 
                                    f"{os.path.splitext(filename)[0]}_ocr.txt")
        logger.info(f"OCR文本文件路径: {ocr_text_path}")
        
        # 检查OCR文本文件是否存在
        if not os.path.exists(ocr_text_path):
            error_msg = f"OCR文本文件不存在: {ocr_text_path}"
            logger.error(error_msg)
            raise HTTPException(status_code=404, detail=error_msg)
            
        # 检查文件是否可读
        if not os.access(ocr_text_path, os.R_OK):
            error_msg = f"OCR文本文件无法读取: {ocr_text_path}"
            logger.error(error_msg)
            raise HTTPException(status_code=403, detail=error_msg)
            
        # 读取OCR文本
        try:
            with open(ocr_text_path, 'r', encoding='utf-8') as f:
                text = f.read()
                
            if not text.strip():
                error_msg = f"OCR文本文件为空: {ocr_text_path}"
                logger.error(error_msg)
                raise HTTPException(status_code=400, detail=error_msg)
                
            logger.info(f"成功读取OCR文本，长度: {len(text)} 字符")
            logger.info(f"OCR文本预览: {text[:200]}...")
            
        except UnicodeDecodeError as e:
            error_msg = f"OCR文本文件编码错误: {str(e)}"
            logger.error(error_msg)
            raise HTTPException(status_code=400, detail=error_msg)
        except Exception as e:
            error_msg = f"读取OCR文本文件失败: {str(e)}"
            logger.error(error_msg)
            raise HTTPException(status_code=500, detail=error_msg)
        
        # 使用LangChain处理文本
        logger.info(f"开始处理文本 - 处理类型: {request.prompt_type}")
        result = langchain_service.process_text(
            text=text,
            prompt_type=request.prompt_type,
            target_language=request.target_language,
            summary_length=request.summary_length if hasattr(request, 'summary_length') else None
        )
        logger.info("文本处理完成")
        
        # 保存结果
        output_filename = f"{os.path.splitext(filename)[0]}_{request.prompt_type}.md"
        output_path = os.path.join(request.temp_dir, "output", output_filename)
        
        with open(output_path, 'w', encoding='utf-8') as f:
            f.write(result)
        logger.info(f"处理结果已保存: {output_path}")
        
        # 返回结果
        response = ProcessResponse(
            status="success",
            message="处理完成",
            result=result,
            output_file=output_filename
        )
        logger.info("请求处理完成，准备返回响应")
        return response
        
    except Exception as e:
        error_msg = f"处理失败: {str(e)}"
        logger.error(error_msg, exc_info=True)
        raise HTTPException(status_code=500, detail=error_msg) 